<?php
namespace Lib;
use Lib\Compressor\CompressorQueue,
    Lib\Compressor\CompressorException;
/**
 * Class description
 *
 * @since 1.0
 * @author Anton Patrikeyev <anton.patrikeyev@gmail.com>
 */
class Compressor {
    /**
     * @var \ArrayObject|null
     */
    protected $_queues = null;

    /**
     * @var string
     */
    private $_extension = 'js';

    /**
     * @var string
     */
    protected $_basePath = 'public/js';

    public function __construct($basePath = null){
        $this->_queues = new \ArrayObject();
        $basePath = (null === $basePath)?$this->getBasePath():$basePath;
        $basePath = realpath(APPLICATION_PATH . '/../' . $basePath);
        $this->setBasePath($basePath);
    }

    /**
     * @throws Compressor\CompressorException
     * @param Compressor\CompressorQueue $queue
     * @param null $name
     * @return void
     */
    public function addQueue(CompressorQueue $queue){
        if(null === $queue->getName()){
            throw new CompressorException('Queue need to have name');
        }
        $this->_queues->offsetSet($queue->getName(), $queue);
    }


    /**
     * @param  $name
     * @return void
     */
    public function removeQueue($name){
        if($this->_queues->offsetExists($name)){
            $this->_queues->offsetUnset($name);
        }
    }

    /**
     * @throws Compressor\CompressorException
     * @param  $name
     * @return Compressor\CompressorQueue
     */
    public function getQueue($name){
        if($this->_queues->offsetExists($name)){
            return $this->_queues->offsetGet($name);
        } else {
            throw new CompressorException('Queue specified by '.(string) $name . 'isn\'t founded');
        }
    }

    /**
     * @param  $name
     * @param string $path
     * @param bool $compress
     * @return void
     */
    public function saveQueue($name, $path = '', $compress = true, $minify = false){
        $this->getQueue($name)->save($this->getExtension(), $path, $compress, $minify);
    }

    /**
     * @param string $path
     * @param bool $compress
     * @return void
     */
    public function save($path = '', $compress = true, $minify = false){
        foreach($this->_queues as $queue){
            $this->saveQueue($queue->getName(), $path, $compress, $minify);
        }
    }

    /**
     * @param  $extension
     * @return void
     */
    public function setExtension($extension) {
        $this->_extension = $extension;
    }

    /**
     * @return string
     */
    public function getExtension() {
        return $this->_extension;
    }

    public function setBasePath($basePath) {
        $this->_basePath = $basePath;
    }

    public function getBasePath() {
        return $this->_basePath;
    }
}